// 封装网络请求

import UIKit
import AFNetworking

// 将一些业务逻辑封装到这个类里 让这个隔离的更加好
class UserAccountViewModel: NSObject {

    // 增加 uesrAccount 属性
    var account: UserAccount?
    
    // 用户是否登录的属性
    var userLogin: Bool {
        return account?.access_token != nil
    }
    
    var token: String? {
        return account?.access_token
    }
    
    var userName : String? {
        return account?.name
    }
    
    //用户头像 url
    var headURL: NSURL? {
        return NSURL(string: (account?.avatar_large ?? ""))
    }
    // 在 init 方法中获取用户账户
    override init() {
        account = UserAccount.loadAccount()
    }
    ////加载用户token
    func loadAccessToken(code: String, finished: (error: NSError?) -> ()) {
        let urlString = "oauth2/access_token"
        let parameters = ["client_id": client_id,"client_secret":client_secret,"grant_type" : "authorization_code","code":code,"redirect_uri":redirect_uri]
        NetworkingTools.sharedTools.requestJsonDict(.POST, urlString: urlString, parmaters: parameters) { (result, error) -> () in
            if error != nil {
                print("--------")
                print(error)
                finished(error: error)
            }
            // 执行成功
            let account = UserAccount(dict: result!)
            self.loadUserInfo(account, finished: finished)
        }
    }
    
    //加载用户信息
    private func loadUserInfo(account: UserAccount,finished: (error: NSError?) -> ()) {
        let urlString = "2/users/show.json"
        let parmaters = ["access_token": account.access_token!, "uid": account.uid!]
        NetworkingTools.sharedTools.requestJsonDict(.GET, urlString: urlString, parmaters: parmaters) { (result, error) -> () in
            if error != nil {
                finished(error: error)
                return
            }
            // 请求用户信息
            account.avatar_large = result!["avatar_large"] as? String
            account.name = result!["name"] as? String
            
            account.saveAcount()
            //执行闭包
            finished(error: nil)
        }
    }
}



